package org.jeecg.config.deepseek;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


import java.util.HashMap;
import java.util.Map;

@Component
public class RequestLimitInterceptor implements HandlerInterceptor {

    private static final int MAX_REQUESTS_PER_DAY = 10;
    private static final long TIME_WINDOW = 24 * 60 * 60L; // 一天的时间窗口，单位秒
    @Autowired
    private final RedisUtil redisUtil;

    public RequestLimitInterceptor(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if (!requestURI.contains("/deepseek")) {
            return true;
        }

        String clientIp = getClientIp(request);
        String redisKey = "visit:ip:" + clientIp;

        Integer currentVisitCount = (Integer) redisUtil.get(redisKey);
        if (currentVisitCount != null && currentVisitCount >= MAX_REQUESTS_PER_DAY) {
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json;charset=UTF-8");
            Map<String, Object> resultMap = new HashMap<>();
//            resultMap.put("status", 429);
            resultMap.put("content", "请联系我们的顾问老师,才能够继续使用此功能");
            String s = new ObjectMapper().writeValueAsString(resultMap);
            response.getWriter().write(s);
            return false;
        }

        // 增加访问次数并设置一天的过期时间
        if (currentVisitCount == null) {
            redisUtil.set(redisKey, 1, TIME_WINDOW); // 第一次访问，设置过期时间
        } else {
            redisUtil.incr(redisKey, 1); // 增加访问次数
        }

        return true;
    }

    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
